package org.poem.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.poem.CommonVO;
import org.poem.IdsVo;
import org.poem.datasource.DataAndParametersVo;
import org.poem.datasource.DataSourceQueryVo;
import org.poem.datasource.DataSourceVo;
import org.poem.datasource.ParametersVo;
import org.poem.handler.impl.CDataSourceServices;
import org.poem.result.CommonResult;
import org.poem.result.PageableResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.List;



@RestController
@RequestMapping("/v1/tDataSource")
@Api(tags = {"31-数据源接口"})
@Slf4j
public class CDataSourceController {

    @Autowired
    private CDataSourceServices cDataSourceServices;


    /**
     * 01-展示数据源管理+分页
     *
     * @param pageSize   分页大小
     * @param pageNumber 页数
     * @return
     */

    @ApiOperation(value = "3101_展示数据源管理-带有分页", notes = "展示数据源管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", required = true, value = "分页大小", dataType = "Integer", paramType = "path", example = "10"),
            @ApiImplicitParam(name = "number", required = true, value = "分页页码", dataType = "Integer", paramType = "path", example = "0")
    })
    @ApiResponses
            ({
                    @ApiResponse(code = 400, message = "请求参数没有填好"),
                    @ApiResponse(code = 404, message = "请求路径没有找到")
            })
    @GetMapping("/findDataSourceList/{size}/{number}")
    @ResponseBody
    public CommonResult<PageableResult<DataSourceVo>> findDataSourceList(Long subjectId, String sourceName,
                                                                         @PathVariable("size") Integer pageSize,
                                                                         @PathVariable("number") Integer pageNumber) {
        DataSourceQueryVo dataSourceQueryVo = new DataSourceQueryVo();
        dataSourceQueryVo.setSourceName(sourceName);
        log.info("CDataSourceController:findDataSourceList:[subjectId]:" + subjectId+"------------"+sourceName + "  [pageSize]:" + pageSize + ", [pageNumber]: " + pageNumber);
        CommonResult<PageableResult<DataSourceVo>> dataSourceList = cDataSourceServices.findDataSourceList(subjectId, sourceName, pageSize, pageNumber);
        return dataSourceList;
    }

    /**
     * 02-新建数据源
     * @param dataSourceVo
     * @return
     */
    @ApiOperation(value = "3102_新建数据源", notes = "新建数据源")
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数没有填好"),
            @ApiResponse(code = 404, message = "请求路径没有找到")
    })
    @PostMapping("/addDataSource")
    @ResponseBody
    public  CommonResult<String> addDataSource(@RequestBody DataAndParametersVo dataSourceVo){
        log.info("CDataSourceController:addDataSource:[dataSourceVo]:" + JSONObject.toJSONString(dataSourceVo));

        List<ParametersVo> parametersVos = dataSourceVo.getParametersVos();

        if(dataSourceVo.getDataSourceVo() != null){
            DataSourceVo dataSourceVo1 = dataSourceVo.getDataSourceVo();
        }
        return cDataSourceServices.addDataSource(dataSourceVo);
    }

    /**
     * 03-根据数据源id查询数据源详情
     * @param dataSourceId   数据源id
     * @return
     */
    @ApiOperation(value = "3103_根据id查询数据源详情", notes = "根据id查询数据源详情")
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数没有填好"),
            @ApiResponse(code = 404, message = "请求路径没有找到")
    })
    @GetMapping("/getDataSourceVoById/{dataSourceId}")
    @ResponseBody
    public CommonResult<DataAndParametersVo> getDataSourceVoById(@PathVariable("dataSourceId") Long dataSourceId){
        log.info("CDataSourceController:getDataSourceVoById:dataSourceId="+dataSourceId);
        return cDataSourceServices.getDataSourceVoById(dataSourceId);
    }

    /**
     * 04-修改数据源
     * @param dataSourceVo
     * @return
     */
    @ApiOperation(value = "3104_修改数据源", notes = "修改数据源")
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数没有填好"),
            @ApiResponse(code = 404, message = "请求路径没有找到")
    })
    @PostMapping("/updateDataSource")
    @ResponseBody
    public CommonResult<String> updateDataSource(@RequestBody DataAndParametersVo dataSourceVo){
        log.info("CDataSourceController:updateDataSource:" + JSON.toJSONString(dataSourceVo));
        return cDataSourceServices.updateDataSource(dataSourceVo);
    }

    /**
     * 05-根据数据源id删除数据源
     * @param dataSourceId   数据源id
     * @return
     */
    @ApiOperation(value = "3105_根据数据源id删除数据源", notes = "根据数据源id删除数据源")
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数没有填好"),
            @ApiResponse(code = 404, message = "请求路径没有找到")
    })
    @PostMapping("/deleteDataSourceById")
    @ResponseBody
    public CommonResult<String> deleteDataSourceById(Long dataSourceId){
        log.info("CDataSourceController:deleteDataSourceById:dataSourceId"+dataSourceId);
        CommonResult<String> stringCommonResult = cDataSourceServices.deleteDataSourceById(dataSourceId);
        return new CommonResult<>(0,null,"删除成功！");
    }

    /**
     * 06-根据数据源id批量删除
     * @param idsVo          数据源id数组
     * @return
     */
    @ApiOperation(value = "3106_根据数据源id批量删除除", notes = "根据数据源id批量删除")
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数没有填好"),
            @ApiResponse(code = 404, message = "请求路径没有找到")
    })
    @PostMapping("/deleteDataSource")
    @ResponseBody
    public CommonResult<String> deleteDataSource(@RequestBody IdsVo idsVo){
        Long[] ids = idsVo.getIds();
        log.info("CDataSourceController:deleteDataSource:ids"+ids.toString());
        return cDataSourceServices.deleteDataSource(idsVo);
    }

    /**
     * 07-导出数据源模板
     * @return
     * @throws UnsupportedEncodingException
     */
    @ApiOperation(value = "3107_导出数据源模板", notes = "导出数据源模板")
    @ApiResponses({@ApiResponse(code = 400, message = "请求参数没有填好"), @ApiResponse(code = 404, message = "请求路径没有找到")})
    @GetMapping(value = "/exportDataSourceTemplate")
    public ResponseEntity<byte[]> exportDataSourceTemplate(){
        ResponseEntity<byte[]> result = null;
        try {
            // feign文件下载
            ResponseEntity<byte[]> response = cDataSourceServices.exportDataSourceTemplate();
            byte[] body = response.getBody();
            HttpHeaders heads = new HttpHeaders();
            heads.add("Content-Disposition", "attachment; filename=\"" + new String("数据源版本导入模板.xls".getBytes(StandardCharsets.UTF_8), "ISO8859-1") + "\"");
            result = new ResponseEntity<byte[]>(body, heads, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }





    /**
     * 10-数据源测试连接
     * @param dataSourceVo
     * @return
     */
    @ApiOperation(value = "3110_数据源测试连接", notes = "数据源测试连接")
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数没有填好"),
            @ApiResponse(code = 404, message = "请求路径没有找到")
    })
    @PostMapping("/testDataSourceConnect")
    @ResponseBody
    public  CommonResult<String> testDataSourceConnect(@RequestBody DataAndParametersVo dataSourceVo){

        log.info("CDataSourceController:testDataSourceConnect:[dataSourceVo]:" + JSONObject.toJSONString(dataSourceVo));
        return cDataSourceServices.testDataSourceConnect(dataSourceVo);
    }


    /**
     * 13-从Redis获取连接池信息
     * @return
     */
    @ApiOperation(value = "3113_获取数据源的列表", notes = "从Redis获取连接池信息")
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数没有填好"),
            @ApiResponse(code = 404, message = "请求路径没有找到")
    })
    @GetMapping("/getDatasourceList/{subjectId}")
    @ResponseBody
    public CommonResult<List<CommonVO>> getDatasourceList(@PathVariable("subjectId") Long subjectId){
        log.info("CDataSourceController:getDatasourceList:subjectId:" +subjectId);
        return cDataSourceServices.getDatasourceList(subjectId);
    }

    /**
     * 10-数据源测试连接
     *
     * @param dataSourceVo
     * @return
     */
    @ApiOperation(value = "3114_获取数据库信息", notes = "获取数据库信息")
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数没有填好"),
            @ApiResponse(code = 404, message = "请求路径没有找到")
    })
    @PostMapping("/getSchema")
    @ResponseBody
    public CommonResult<List<String>> getSchema(@RequestBody DataAndParametersVo dataSourceVo) {
        log.info("CDataSourceController:getSchema:[dataSourceVo]:" + JSONObject.toJSONString(dataSourceVo));
        return this.cDataSourceServices.getSchema(dataSourceVo);
    }


    /**
     * 13-从Redis获取连接池信息
     * @return
     */
    @ApiOperation(value = "3115_获取数据源的列表", notes = "从Redis获取连接池信息")
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数没有填好"),
            @ApiResponse(code = 404, message = "请求路径没有找到")
    })
    @GetMapping("/getDatasourceList/{subjectId}/{datasourceTypeId}")
    @ResponseBody
    public CommonResult<List<CommonVO>> getDatasourceList(@PathVariable("subjectId") Long subjectId, @PathVariable("datasourceTypeId") Long datasourceTypeId) {
        log.info("CDataSourceController:getDatasourceList:subjectId:" + subjectId + " datasourceTypeId:" + datasourceTypeId);
        return cDataSourceServices.getDatasourceList(subjectId, datasourceTypeId);
    }
}
